package com.lvmama.controller.dw.priceStock;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.lvmama.client.dw.StockClient;
import com.lvmama.common.constants.Constants;
import com.lvmama.common.result.CodeMessage;
import com.lvmama.common.result.Result;
import com.lvmama.common.utils.DateUtil;
import com.lvmama.common.utils.ExportExcelUtils;
import com.lvmama.common.utils.JSONConversionUtil;
import com.lvmama.common.utils.PageInfoUtil;
import com.lvmama.pojo.dto.dw.StockDetailQuery;
import com.lvmama.pojo.entity.dw.priceStock.StockDetail;

@Controller
@RequestMapping("stock")
@Slf4j
public class StockController {
    @Autowired
    private StockClient stockClient;

    @RequestMapping("detail")
    public String detail(ModelMap model) {
    	setModel(model);
        return "dw/stock/stockDetail";
    }
    
    @RequestMapping("stockGather")
    public String stock(ModelMap model) {
    	setModel(model);
    	return "dw/stock/stockGather";
    }
    
	/**
	 * 设置model值
	 * @param model
	 */
    private void setModel(ModelMap model){
    	String[] latestDays = DateUtil.getFutureDays(29,Constants.DESC);
		List<String> days = new ArrayList<>();
		for (String day : latestDays) {
			days.add(day.substring(5, 10));
		}
		String day = JSONConversionUtil.objToString(days);
		model.addAttribute("days", day);
		model.addAttribute("currentDays", days);
    }
    
    @RequestMapping("detailSearch")
    @ResponseBody
    public Result<List<Long>> detailSearch(@RequestBody StockDetailQuery query ) {
        //查询库存详情
        return getStockNumByQuery(query, false);
    }

    @RequestMapping("gatherSearch")
    @ResponseBody
    public Result<List<Long>> gatherSearch(@RequestBody StockDetailQuery query ) {
        //查询库存详情
        return getStockNumByQuery(query, true);
    }

    /**
     * 获取echart显示的数据
     * @param query
     * @param needRedis
     * @return
     */
    private Result<List<Long>> getStockNumByQuery(StockDetailQuery query, Boolean needRedis){
    	try {
			StockDetail stockDetail = null;
			try {
				if (needRedis){
					stockDetail = stockClient.selectStockDetailRedis(query).getData().get(0);
				}else{
					stockDetail = stockClient.selectStockDetail(query).getData().get(0);
				}
			} catch (Exception e) {
				log.error(e.getMessage());
			}
    		

            if (stockDetail == null){
            	return Result.error(CodeMessage.DATA_ERROR);
			}
            //获取对象所有的属性值放到集合中
            Field[] fields = stockDetail.getClass().getDeclaredFields();
            List<Long> stockNums = new ArrayList<>();
            if (fields == null || fields.length == 0){
            	return Result.error(CodeMessage.SERVER_ERROR);
			}
            String parDay = null;
            for (Field field : fields) {
                field.setAccessible(true);
				String fieldName = field.getName();
				if(fieldName.startsWith("stock") && !fieldName.equals("stock1")){
					Long  stockNum = (Long) field.get(stockDetail);
					stockNums.add(stockNum);
				}else if (fieldName.startsWith("parDay")){
					parDay = ((String)field.get(stockDetail));
				}
            }

            Result<List<Long>> responseVo = Result.success(stockNums);
            responseVo.setMessage(parDay);
            return responseVo;
        }catch (IllegalAccessException e){
            log.error("detail error:{}" + e.getMessage(), e);
        }
    	return Result.error(CodeMessage.SERVER_ERROR);
    }
    
    /**
     * 各类明细查询
     * @param query
     * @return
     */
    @RequestMapping("search")
    @ResponseBody
    public Result<List<StockDetail>> search(@RequestBody StockDetailQuery query){
    	try {
    		List<StockDetail> list = this.stockClient.selectStockDetail(query).getData();
    		if (list == null || list.size() == 0){
    			return Result.error(CodeMessage.DATA_ERROR);
    		}
    		return Result.success(list);
		} catch (Exception e) {
			log.error("detail error:{}" + e.getMessage(), e);
		}
    	return Result.error(CodeMessage.SERVER_ERROR);
    }
	/**
	 * 导出汇总excel
	 * @param query
	 * @return
	 */
	@RequestMapping("exportStockGather")
	public void exportStockGather( StockDetailQuery query, HttpServletResponse response){
		List<StockDetail> list = null;
		try {
			//如果是大区先取分页中的数据
			if (query.getGroupByRegionname()){
				query.setPageSize(100);
				PageInfoUtil<StockDetail> page = this.stockClient.selectStockDetailPageByRedis(query).getData();
				list = page.getList();
			}else {
				list = this.stockClient.selectStockDetailRedis(query).getData();
			}
		} catch (Exception e) {
			log.error("detail error:{}" + e.getMessage(), e);
		}
		
		exportExcel(query, response, list, false);
	}
	/**
	 * 导出明细excel
	 * @param query
	 * @return
	 */
	@RequestMapping("exportStockDetail")
	public void exportStockDetail( StockDetailQuery query, HttpServletResponse response){
		//如果是大区先取分页中的数据
		List<StockDetail> list = this.stockClient.selectStockDetail(query).getData();
		exportExcel(query, response, list, true);
	}

	/**
	 * 导出excel方法
	 * @param query
	 * @param response
	 * @param list
	 * @param isDetail
	 */
	private void exportExcel(StockDetailQuery query, HttpServletResponse response, List<StockDetail> list, boolean isDetail){
		//导出excel文件
		ExportExcelUtils<StockDetail> ex = new ExportExcelUtils<StockDetail>();
		String title = getExcelTitle(query);
		//生成日期
		String[] latestDays = DateUtil.getFutureDays(29,Constants.DESC);
		String[] headers = new String[latestDays.length + 1];
		headers[0] = title;
		int j = 1;
		//生成excel头列表
		for (String day : latestDays){
			headers[j++] = day;
		}
		OutputStream fOut = null;
		try {
			// 生成提示信息，
			response.setContentType("application/vnd.ms-excel");
			// 是否是明细
			if (isDetail){
				title = "库存明细-" + title;
			}else{
				title = "库存汇总-" + title;
			}
			// 进行转码，使其支持中文文件名
			String codedFileName = java.net.URLEncoder.encode( title + "统计文档", "UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
			fOut = response.getOutputStream();
			Field[] fields = getFields(headers, query);
			ex.exportExcel(title, headers, fields, list, fOut, "yyyy-MM-dd");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private String getExcelTitle(StockDetailQuery query){
		String title = "";
		if (query.getGroupByBranch()){
			title = "房型";
		}else  if(query.getGroupByCategory()){
			title = "品类";
		}else  if(query.getGroupByChannel()){
			title = "渠道";
		}else  if(query.getGroupByRegionname()){
			title = "大区";
		}else  if(query.getGroupByHotle()){
			title = "酒店";
		}
		return title;

	}
	/**
	 * 根据每列字段名称创建需要导出字段的数组
	 *
	 * @param headers
	 * @param query
	 * @return
	 */
	private Field[] getFields(String[] headers, StockDetailQuery query) {
		Field[] fields = new Field[headers.length];
		//获取对象所有的属性值放到集合中
		StockDetail t = new StockDetail();
		Field[] fieldList = t.getClass().getDeclaredFields();
		try {
			if (query.getGroupByBranch()){
				fields[0] = t.getClass().getDeclaredField("branchName");
			}else  if(query.getGroupByCategory()){
				fields[0] = t.getClass().getDeclaredField("categoryName");
			}else  if(query.getGroupByChannel()){
				fields[0] = t.getClass().getDeclaredField("saleChannel");
			}else  if(query.getGroupByRegionname()){
				fields[0] = t.getClass().getDeclaredField("regionname");
			}else  if(query.getGroupByHotle()){
				fields[0] = t.getClass().getDeclaredField("productName");
			}
			int i = 1;
			for (Field field : fieldList) {
				String fieldName = field.getName();
				if(fieldName.startsWith("stock") && !fieldName.equals("stock1")){
					fields[i] = field;
					System.out.println(fieldName);
					i ++;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return fields;
	}
    /**
     * 各类明细查询
     * @param query
     * @return
     */
    @RequestMapping("searchRedis")
    @ResponseBody
    public Result<List<StockDetail>> searchRedis(@RequestBody StockDetailQuery query){
    	try {
    		List<StockDetail> list = this.stockClient.selectStockDetailRedis(query).getData();
    		if (list == null || list.size() == 0){
    			return Result.error(CodeMessage.DATA_ERROR);
    		}
    		
    		return Result.success(list);
		} catch (Exception e) {
			log.error("detail error:{}" + e.getMessage(), e);
		}
    	return Result.error(CodeMessage.SERVER_ERROR);
    }

    /**
     * 各类明细分页查询
     * @param query
     * @return
     */
    @RequestMapping("searchPage")
    @ResponseBody
    public Result<PageInfo<StockDetail>> searchPage(@RequestBody StockDetailQuery query){
    	try {
    		PageInfo<StockDetail> page = this.stockClient.selectStockDetailPage(query).getData();
    		if (page == null || page.getList() == null || page.getList().size() == 0){
    			return Result.error(CodeMessage.DATA_ERROR);
    		}
    		
    		return Result.success(page);
    	} catch (Exception e) {
    		log.error("detail error:{}" + e.getMessage(), e);
    	}
    	
    	return Result.error(CodeMessage.SERVER_ERROR);
    }

    /**
     * 各类明细分页查询
     * @param query
     * @return
     */
    @RequestMapping("searchPageUtil")
    @ResponseBody
    public Result<PageInfoUtil<StockDetail>> searchPageUtil(@RequestBody StockDetailQuery query){
    	try {
    		PageInfoUtil<StockDetail> page = this.stockClient.selectStockDetailPageByRedis(query).getData();
    		if (page == null || page.getList() == null || page.getList().size() == 0){
    			return Result.error(CodeMessage.DATA_ERROR);
    		}
    		return Result.success(page);
    	} catch (Exception e) {
    		log.error("detail error:{}" + e.getMessage(), e);
    	}

    	return Result.error(CodeMessage.SERVER_ERROR);
    }

    
   
    

}
